package com.study.ktandroid.coroutines_apply.apply.ui

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.study.ktandroid.coroutines_apply.apply.bean.LoadState
import com.study.ktandroid.coroutines_apply.apply.vm.MainViewModel
import com.study.ktandroid.databinding.ActivityCoroApplyBinding
import org.jetbrains.anko.sdk27.coroutines.onClick

/**
 * 协程的实际应用
 */
class CoroApplyActivity : AppCompatActivity() {

    lateinit var mainViewModel: MainViewModel

    lateinit var binding: ActivityCoroApplyBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCoroApplyBinding.inflate(layoutInflater)
        setContentView(binding.root)
        mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]

        mainViewModel.loadState.observe(this, {
            when (it) {
                is LoadState.Loading -> binding.button.isEnabled = false
                is LoadState.Success -> binding.button.isEnabled = true
                is LoadState.Fail -> {
                    binding.button.isEnabled = true
                    ToastUtils.showLong(it.msg)
                }
            }
        })

        mainViewModel.imageList.observe(this, {
            Glide.with(this)
                    .load(it[0]).into(binding.imageView1)
            Glide.with(this)
                    .load(it[1]).into(binding.imageView1)
            Glide.with(this)
                    .load(it[2]).into(binding.imageView1)
        })

        binding.button.onClick {
            mainViewModel.getData()
        }
    }
}